﻿namespace Devonline.AspNetCore;

/// <summary>
/// 简易的事件流程模型
/// </summary>
/// <typeparam name="TEventArgs"></typeparam>
public class EventPipeline<TEventArgs>
{
    /// <summary>
    /// 单实例构造方法
    /// </summary>
    private EventPipeline() { }
    /// <summary>
    /// 数据订阅事件
    /// </summary>
    private static readonly Dictionary<string, EventHandler<TEventArgs>> _eventHandlers = [];

    /// <summary>
    /// 返回事件管道单例
    /// </summary>
    public static EventPipeline<TEventArgs> Instance { get; } = new();
    /// <summary>
    /// 订阅事件
    /// </summary>
    /// <param name="eventName"></param>
    /// <param name="eventHandler"></param>
    public void Subscribe(string eventName, EventHandler<TEventArgs> eventHandler)
    {
        if (!_eventHandlers.TryAdd(eventName, eventHandler))
        {
            _eventHandlers[eventName] += eventHandler;
        }
    }
    /// <summary>
    /// 发布 eventName 管道事件
    /// </summary>
    /// <param name="eventName">执行事件名称</param>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    public void Publish(string eventName, object? sender, TEventArgs args)
    {
        if (_eventHandlers.TryGetValue(eventName, out var hander))
        {
            hander(sender, args);
        }
    }
}